package cn.imvc.app.jobs;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import cn.imvc.app.entities.Goods;
import cn.imvc.app.models.GoodsSkuModel;
import cn.imvc.app.repositories.GoodsLimitTimeRepository;
import cn.imvc.app.repositories.GoodsRepository;
@DisallowConcurrentExecution
public class GoodsLimitTimeQuarz{
	@Autowired
	GoodsSkuModel goodsSkuModel;
	@Autowired
	GoodsRepository goodsRepository;
	@Autowired
	GoodsLimitTimeRepository goodsLimitTimeRepository;
	/**
	 * 自动上下线产品(5分钟)
	 * @param context
	 */
	public void autoEnableOrDisableGoods(JobExecutionContext context) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String nowStr = dateFormat.format(new Date());
		//查询需下线的
		List<Object[]> objsList = goodsLimitTimeRepository.findAllSql("select g.id as gid,gl.id as glid from goods_limit_time gl left join goods g on gl.goodsId = g.id where gl.startTime > '"+nowStr
				+"' and gl.endTime < '"+nowStr+"' and g.state = 1");
		Iterator<Object[]> iterator = objsList.iterator();
		while (iterator.hasNext()) {
			Object[] objs = (Object[]) iterator.next();
			int gid = Integer.valueOf(objs[0].toString());
			Goods goods = goodsRepository.findOne(gid);
			goods.setState((byte)0);
			goodsSkuModel.updateSkuState(goods);
			goodsRepository.saveAndFlush(goods);
		}
		//查询需上线的
		objsList = goodsLimitTimeRepository.findAllSql("select g.id as gid,gl.id as glid from goods_limit_time gl left join goods g on gl.goodsId = g.id where gl.startTime < '"+nowStr
				+"' and gl.endTime > '"+nowStr+"' and g.state = 0");
		iterator = objsList.iterator();
		while (iterator.hasNext()) {
			Object[] objs = (Object[]) iterator.next();
			int gid = Integer.valueOf(objs[0].toString());
			Goods goods = goodsRepository.findOne(gid);
			goods.setState((byte)1);
			goodsSkuModel.updateSkuState(goods);
			goodsRepository.saveAndFlush(goods);
		}
		
		
		System.out.println("限时购任务完成！！");
	}
}
